package com.mano.mall.service.good.impl;

import com.mano.mall.api.dto.good.output.ProductOutputDTO;
import com.mano.mall.api.good.ProductSearchService;
import com.mano.mall.common.base.BaseApiService;
import com.mano.mall.common.base.BaseResponse;
import com.mano.mall.common.mapper.MapperUtils;
import com.mano.mall.elk.log.annotation.ServiceLog;
import com.mano.mall.service.mapper.ProductReposiory;
import com.mano.mall.service.mapper.entity.ProductEntity;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: zj
 * @Description:
 * @Date: Created in 16:14 2020/10/15
 * @Modified By:
 */
@RestController
public class ProductSearchServiceImpl extends BaseApiService<List<ProductOutputDTO>> implements ProductSearchService {

    @Autowired
    private ProductReposiory productReposiory;


    @ServiceLog
    @Override
    @HystrixCommand(fallbackMethod = "defaultCallBackMethod")
    public BaseResponse<List<ProductOutputDTO>> search(String name) {

//        int i=1/0;
        BoolQueryBuilder builder = QueryBuilders.boolQuery();

//        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//        queryBuilder.withQuery(QueryBuilders.multiMatchQuery(name, "title","sell_point"));
//        queryBuilder.withQuery(QueryBuilders.rangeQuery("price").lt(500000).gt(100000));
        // 模糊查询 name 字段
//        builder.must(QueryBuilders.fuzzyQuery("name",name));

        // 模糊查询 name  匹配的字段 name  subtitle detail  都可以
        builder.must(QueryBuilders.multiMatchQuery(name,"name","subtitle","detail"));

        // 分頁
        QPageRequest pageable = new QPageRequest(0, 5);


        Page<ProductEntity> page = productReposiory.search(builder, pageable);

        List<ProductEntity> content = page.getContent();

        List<ProductOutputDTO> mapAsList = MapperUtils.mapAsList(content, ProductOutputDTO.class);

        return setResultSuccess(mapAsList);
    }
}
